package org.jdns.jfreechess.ics;

import java.util.Set;

import com.google.common.collect.Sets;
import com.google.common.util.concurrent.AbstractExecutionThreadService;

public class IcsMessageDispatcher extends AbstractExecutionThreadService {
  private final Set<IcsMessageHandler> messageHandlers = Sets.newLinkedHashSet();
  private IcsMessageReader reader;

  public IcsMessageDispatcher(IcsMessageReader reader) {
    this.reader = reader;
  }

  public void addIcsMessageHandler(IcsMessageHandler handler) {
    messageHandlers.add(handler);
  }

  public void removeIcsMessageHandler(IcsMessageHandler handler) {
    messageHandlers.remove(handler);
  }

  @Override
  protected void run() throws Exception {
    String message;

    while ((message = reader.readMessage()) != null) {
      IcsMessage icsMessage = new IcsMessage(message);
      fireMessageReceived(icsMessage);
    }
  }

  private void fireMessageReceived(IcsMessage icsMessage) {
    for (IcsMessageHandler handler : messageHandlers) {
      handler.messageReceived(icsMessage);
    }
  }
}
